package com.example.wjy.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.superyi.myteam.databinding.FragmentMasterBinding;
import com.example.wjy.adapter.MasterAdapter;
import com.example.wjy.viewmodels.MasterViewModel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * 在此碎片中使用recyclerView显示符合某种标签的大神列表
 */
public class MasterFragment extends Fragment {

    /**
     * The adapter of RecyclerView in this fragment.
     */
    MasterAdapter masterAdapter;

    /**
     * The viewModel of this fragment to control data stream from database.
     */
    MasterViewModel masterViewModel;


    /**
     * DataBinding of this fragment and fragment_master.
     */
    FragmentMasterBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentMasterBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        masterViewModel = new ViewModelProvider(requireActivity()).get(MasterViewModel.class);

        //从masterViewModel中获取Livedata类型的数据列表
        masterAdapter = new MasterAdapter(masterViewModel.getMasterLive().getValue());
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false));
        binding.recyclerView.setAdapter(masterAdapter);

        //对该列表进行观察，一旦有变化，通知Recyclerview刷新界面
        masterViewModel.getMasterLive().observe(requireActivity(), masters -> {
            masterAdapter.setMasterList(masters);
            masterAdapter.notifyDataSetChanged();
        });

        masterViewModel.getMaster().observe(requireActivity(),masters -> {
            masterAdapter.setMasterList(masters);
            masterAdapter.notifyDataSetChanged();
        });
    }
}